//
//  WBBaseViewController.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/6/29.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import UIKit

class WBBaseViewController: UIViewController {
    lazy var navigationbar: UINavigationBar = UINavigationBar(frame:CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    
    /// 实例化导航条目 - 所有的按钮都加载到条目上的
    lazy var navItem: UINavigationItem = UINavigationItem()
    /// 懒加载表格视图
    var tableView: UITableView?
    /// 刷新控件 懒加载
    lazy var refreshControl = UIRefreshControl()
    /// 是否是上拉刷新
    var isPullUp = false
    /// 访客信息字典
    var visitInfoDict: [String: String]?
    /// title 的setter方法
    override var title: String?  {
        didSet {
            navItem.title = title
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.cz_random()
        
        setupUI()
        // 判断用户是否登录, 登录了才加载数据, 如果为登录不加载数据
        WebNetworkTools.shared.userLogon ? loadData() : ()
        // 注册通知
        NotificationCenter.default().addObserver(self, selector: #selector(userLoginSuccessNotification), name: WBUserLoginSuccessNotification, object: nil)
    }
   
    // 注册操作
   @objc private func registerAction() {
        print("注册")
    }
    /// 登录操作
    @objc private func loginAction() {
        print("登录")
        // 发送用户需要登录的通知 -- 通知是一处广播,多处监听对号入座, 一对多的关系
        NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserShouldLogonNotification), object: nil)
    }
    
    @objc private func userLoginSuccessNotification(n:NSNotification) {
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        // 登录成功切换访客视图到主页面
        // 当视图为nil, 系统会调用loadView方法,
        view = nil
        NotificationCenter.default().removeObserver(self)
        
    }
    
    deinit {
        // 注销通知
        NotificationCenter.default().removeObserver(self)
    }
}

extension WBBaseViewController {
    // MARK: - 准备加载数据的空方法
   @objc func loadData() {
        refreshControl.endRefreshing()
    
    }
  private func setupUI() {
        automaticallyAdjustsScrollViewInsets = false
        setupNavigationBar()
        //判断是否登录
       WebNetworkTools.shared.userLogon ? setupTableView() : setupVisitView()
    }
    
    func setupVisitView() {
        let visitView = WBVisitView(frame:view.bounds)
        view.insertSubview(visitView, at: 0)
        visitView.userInfo = visitInfoDict
        visitView.registerButton.addTarget(self, action: #selector(registerAction), for: .touchUpInside)
        
         visitView.loginButton.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册",fontSize: 16, normalColor: #colorLiteral(red: 0.9101451635, green: 0.2575159371, blue: 0.1483209133, alpha: 1), target: self,action: #selector(registerAction), isBack: true)
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", fontSize: 16, target: self, action: #selector(loginAction))
        
    }
    
    func setupTableView() {
        refreshControl.tintColor = #colorLiteral(red: 0.8949507475, green: 0.1438436359, blue: 0.08480125666, alpha: 1)
        tableView = UITableView(frame: self.view.bounds, style: .plain)
        tableView?.contentInset = UIEdgeInsets(top: navigationbar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        // 添加表视图 一定要有才可以添加 - 所以必须强行解包
        view.insertSubview(tableView!, belowSubview: navigationbar)
        // 修改指示器的位置, 缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
    }
    
    // MARK: - 设置导航条 自定义
     func setupNavigationBar() {
        view.addSubview(navigationbar)
        navigationbar.items = [navItem]
        /// 这是设置导航条文本的渲染颜色
        navigationbar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        navigationbar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray()]
        
    }
}

// MARK: - 实现数据源方法
extension WBBaseViewController: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    // 将要显示的indexPath.row 行的cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let count = tableView.numberOfSections - 1
        let rowCount = tableView.numberOfRows(inSection: count)
        
        if row < 0 || count < 0 {
            return
        }
        
        if row == (rowCount - 1) && !isPullUp {
            loadData()
            self.isPullUp = true
        }
    }
}

